package com.hk.huakangcompany.service.impl;

import com.github.pagehelper.PageHelper;
import com.hk.huakangcompany.mapper.WxRoleMapper;
import com.hk.huakangcompany.model.WxRole;
import com.hk.huakangcompany.model.WxRolePermissionRelation;
import com.hk.huakangcompany.service.WxRolePermissionRelationService;
import com.hk.huakangcompany.service.WxRoleService;
import com.hk.huakangcompany.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/26 10:42
 * @Statement: 角色服务接口
 */
@Slf4j
@Service
public class WxRoleServiceImpl implements WxRoleService {


    @Autowired
    private WxRoleMapper roleMapper;

    @Autowired
    private WxRolePermissionRelationService rolePermissionRelationService;

    @Override
    public List<WxRole> findAll(Integer page, Integer limit, WxRole t) {
        PageHelper.startPage(page,limit);
        List<WxRole> roleList = roleMapper.findAll(t);
        return roleList;
    }

    @Override
    public int count(Integer page, Integer limit, WxRole t) {
        int count = roleMapper.count(t);
        return count;
    }

    @Override
    public WxRole findById(Integer id) {
        WxRole role = roleMapper.findById(id);
        return role;
    }

    @Override
    public List<WxRole> findByIds(List<Integer> roleIds) {
        List<WxRole> roleList = roleMapper.findByIds(roleIds);
        return roleList;
    }

    @Override
    public int save(WxRole t) {
        //        修改日期时间
        String dateTimeString = DateUtils.dateTimeString(new Date());
        t.setGmtCreate(dateTimeString);
        int save = roleMapper.save(t);
        if (save == 1) {
            log.error("添加角色成功！");
        }
        return save;
    }

    @Override
    public int update(WxRole t) {
        int update = roleMapper.update(t);
        if (update == 1) {
            log.error("修改角色成功！");
        }
        return update;
    }

    /**
     * 1、通过角色Id查询是否具有哦相关权限
     * 2、有所属权限，先删除权限关联关系，无 则 忽略该步骤
     * 3、通过角色Id删除角色
     * @param id
     * @return
     */
    @Transactional
    @Override
    public int delete(Integer id) {
        List<WxRolePermissionRelation> rolePermissionRelationList = rolePermissionRelationService.findByRoleId(id);
//        1、判断是否具有所属权限关系 true 不具有权限关系
        if (rolePermissionRelationList.isEmpty()) {
//            2、删除该角色
            int delete = roleMapper.delete(id);
            if (delete == 1) {
                log.error("角色删除成功！");
            }
            return delete;
        }
//        2、删除所属权限关系
        rolePermissionRelationService.deleteByRoleId(id);
//        3、删除该角色
        int delete = roleMapper.delete(id);
        if (delete == 1) {
            log.error("角色删除成功！");
        }
        return delete;
    }


}
